function makeMenuEntry(text)
{
	var e = document.createElement('div');
	e.style.height = '50px';
	e.style.backgroundColor = 'black';
	e.style.border = '1px solid gray';
	e.style.paddingLeft = '10px';
	e.style.margin = '5px 0px';
	e.style.marginLeft = '2px';
	e.style.width = '98%';
	e.addEventListener('mouseover',function(){this.style.background = 'gray';});
	e.addEventListener('mouseout',function(){this.style.background = 'black';});
	e.innerHTML = text;
	return e;
}

function makeEpisodeEntry(episode)
{
	var ep = makeMenuEntry("<p>" + episode + "<br />" + game[episode].length + " Episodes </p");
	ep.addEventListener('click',function(){showEpisodeMenu(episode);});
	return ep;
}

function showEpisodeMenu(episode)
{
	var d = episodeDivs[episode];
	menu.parentNode.removeChild(menu);
	placeMenu(d);
}

function makeLevelEntry(episode,ln)
{
	var le = makeMenuEntry("<p>" + episode + " Level " + ln + "</p>");
	le.addEventListener('click',function(){showCanvas(episode,ln);});
	return le;
}

function showCanvas(e,ln)
{
	var d = episodeDivs[e];
	d.style.display = 'none';
	canvas.style.display = 'inline-block';
	changeLevel(e,ln);
}

function onBackSpace()
{
	var d = episodeDivs[game.episode];
	if(canvas.style.display != 'none')
	{
		canvas.style.display = 'none';
		d.style.display = 'inline-block';
	}
	else if(d.parentNode)
	{
		d.parentNode.removeChild(d);
		placeMenu(menu);
	}
}

function menuStyle(menu)
{
	menu.style.width = canvas.width + "px";
	menu.style.height = canvas.height + "px";
	menu.style.overflow = 'auto';
	menu.style.background = 'black';
	menu.style.display = 'inline-block';
	menu.style.color = 'white';
}

function makeMenuDiv()
{
	var menu = document.createElement('div');
	menuStyle(menu);
	return menu;
}

var episodeList = ["microban"];
var episodeDivs = {};
var menu;

function makeMenu()
{
	menu = document.getElementById('menu');
	menuStyle(menu);
	for(var i = 0;i < episodeList.length;i++)
		if(game[episodeList[i]] == undefined)
		{
			getEpisode(episodeList[i]);
			menu.appendChild(makeEpisodeEntry(episodeList[i]));
			episodeDivs[episodeList[i]] = makeMenuDiv();
			for(var j = 0;j < game[episodeList[i]].length;j++)
				episodeDivs[episodeList[i]].appendChild(makeLevelEntry(episodeList[i],j + 1));
		}
}

function placeMenu(menu)
{
	var c = [];
	var j = 0;
	var parent = canvas.parentNode;
	while(parent.children.length)
	{
		c.push(parent.children[0]);
		parent.removeChild(parent.children[0]);
	}
	for(j = 0;j < c.length;j++)
	{
		parent.appendChild(c[j]);
		if(c[j].nodeName == "CANVAS")
			parent.appendChild(menu);
	}
}

function showMenu()
{
	canvas.style.display = 'none';
	if(menu == undefined)
		makeMenu();

	menu.parentNode.removeChild(menu);
	placeMenu(menu);
}
